{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# readwrite module pgmpy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "pgmpy is a python library for creation, manipulation and implementation of Probabilistic graph models. There are various standard file formats for representing PGM data. PGM data basically consists of graph, a distribution assoicated to each node and a few other attributes of a graph.\n",
    "\n",
    "pgmpy has a functionality to read networks from and write networks to these standard file formats. Currently pgmpy supports 5 file formats ProbModelXML, PomDPX, XMLBIF, XMLBeliefNetwork and UAI file formats. Using these modules, models can be specified in a uniform file format and readily converted to bayesian or markov model objects. \n",
    "\n",
    "Now, Let's read a ProbModel XML File and get the corresponding model instance of the probmodel.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pgmpy.readwrite import ProbModelXMLReader"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [],
   "source": [
    "reader_string = ProbModelXMLReader('../files/example.pgmx')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now to get the corresponding model instance we need `get_model`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = reader_string.get_model()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can query this model accoring to our requirements. It is an instance of BayesianModel or MarkovModel depending on the type of the model which is given.\n",
    "\n",
    "Suppose we want to know all the nodes in the given model, we can do:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['X-ray', 'Bronchitis', 'Dyspnea', 'VisitToAsia', 'Smoker', 'LungCancer', 'Tuberculosis', 'TuberculosisOrCancer']\n"
     ]
    }
   ],
   "source": [
    "print(model.nodes())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get all the edges we can use `model.edges` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "OutEdgeView([('Bronchitis', 'Dyspnea'), ('VisitToAsia', 'Tuberculosis'), ('Smoker', 'Bronchitis'), ('Smoker', 'LungCancer'), ('LungCancer', 'TuberculosisOrCancer'), ('Tuberculosis', 'TuberculosisOrCancer'), ('TuberculosisOrCancer', 'Dyspnea'), ('TuberculosisOrCancer', 'X-ray')])"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.edges()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get all the cpds of the given model we can use `model.get_cpds` and to get the corresponding values we can iterate over each cpd and call the corresponding `get_cpd` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "+----------------------+-------------------------+-------------------------+\n",
      "| TuberculosisOrCancer | TuberculosisOrCancer(0) | TuberculosisOrCancer(1) |\n",
      "+----------------------+-------------------------+-------------------------+\n",
      "| X-ray(0)             | 0.95                    | 0.05                    |\n",
      "+----------------------+-------------------------+-------------------------+\n",
      "| X-ray(1)             | 0.02                    | 0.98                    |\n",
      "+----------------------+-------------------------+-------------------------+\n",
      "+---------------+-----------+-----------+\n",
      "| Smoker        | Smoker(0) | Smoker(1) |\n",
      "+---------------+-----------+-----------+\n",
      "| Bronchitis(0) | 0.7       | 0.3       |\n",
      "+---------------+-----------+-----------+\n",
      "| Bronchitis(1) | 0.4       | 0.6       |\n",
      "+---------------+-----------+-----------+\n",
      "+----------------------+-------------------------+-------------------------+-------------------------+-------------------------+\n",
      "| TuberculosisOrCancer | TuberculosisOrCancer(0) | TuberculosisOrCancer(0) | TuberculosisOrCancer(1) | TuberculosisOrCancer(1) |\n",
      "+----------------------+-------------------------+-------------------------+-------------------------+-------------------------+\n",
      "| Bronchitis           | Bronchitis(0)           | Bronchitis(1)           | Bronchitis(0)           | Bronchitis(1)           |\n",
      "+----------------------+-------------------------+-------------------------+-------------------------+-------------------------+\n",
      "| Dyspnea(0)           | 0.9                     | 0.1                     | 0.3                     | 0.7                     |\n",
      "+----------------------+-------------------------+-------------------------+-------------------------+-------------------------+\n",
      "| Dyspnea(1)           | 0.2                     | 0.8                     | 0.1                     | 0.9                     |\n",
      "+----------------------+-------------------------+-------------------------+-------------------------+-------------------------+\n",
      "+----------------+------+\n",
      "| VisitToAsia(0) | 0.99 |\n",
      "+----------------+------+\n",
      "| VisitToAsia(1) | 0.01 |\n",
      "+----------------+------+\n",
      "+-----------+-----+\n",
      "| Smoker(0) | 0.5 |\n",
      "+-----------+-----+\n",
      "| Smoker(1) | 0.5 |\n",
      "+-----------+-----+\n",
      "+---------------+-----------+-----------+\n",
      "| Smoker        | Smoker(0) | Smoker(1) |\n",
      "+---------------+-----------+-----------+\n",
      "| LungCancer(0) | 0.99      | 0.01      |\n",
      "+---------------+-----------+-----------+\n",
      "| LungCancer(1) | 0.9       | 0.1       |\n",
      "+---------------+-----------+-----------+\n",
      "+-----------------+----------------+----------------+\n",
      "| VisitToAsia     | VisitToAsia(0) | VisitToAsia(1) |\n",
      "+-----------------+----------------+----------------+\n",
      "| Tuberculosis(0) | 0.99           | 0.01           |\n",
      "+-----------------+----------------+----------------+\n",
      "| Tuberculosis(1) | 0.95           | 0.05           |\n",
      "+-----------------+----------------+----------------+\n",
      "+-------------------------+-----------------+-----------------+-----------------+-----------------+\n",
      "| LungCancer              | LungCancer(0)   | LungCancer(0)   | LungCancer(1)   | LungCancer(1)   |\n",
      "+-------------------------+-----------------+-----------------+-----------------+-----------------+\n",
      "| Tuberculosis            | Tuberculosis(0) | Tuberculosis(1) | Tuberculosis(0) | Tuberculosis(1) |\n",
      "+-------------------------+-----------------+-----------------+-----------------+-----------------+\n",
      "| TuberculosisOrCancer(0) | 1.0             | 0.0             | 0.0             | 1.0             |\n",
      "+-------------------------+-----------------+-----------------+-----------------+-----------------+\n",
      "| TuberculosisOrCancer(1) | 0.0             | 1.0             | 0.0             | 1.0             |\n",
      "+-------------------------+-----------------+-----------------+-----------------+-----------------+\n"
     ]
    }
   ],
   "source": [
    "cpds = model.get_cpds()\n",
    "for cpd in cpds:\n",
    "    print(cpd)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "pgmpy not only allows us to read from the specific file format but also helps us to write the given model into the specific file format.\n",
    "Let's write a sample model into Probmodel XML file.\n",
    "\n",
    "For that first define our data for the model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "edges_list = [('VisitToAsia', 'Tuberculosis'),\n",
    "              ('LungCancer', 'TuberculosisOrCancer'),\n",
    "              ('Smoker', 'LungCancer'),\n",
    "              ('Smoker', 'Bronchitis'),\n",
    "              ('Tuberculosis', 'TuberculosisOrCancer'),\n",
    "              ('Bronchitis', 'Dyspnea'),\n",
    "              ('TuberculosisOrCancer', 'Dyspnea'),\n",
    "              ('TuberculosisOrCancer', 'X-ray')]\n",
    "nodes = {'Smoker': {'States': {'no': {}, 'yes': {}},\n",
    "                    'role': 'chance',\n",
    "                    'type': 'finiteStates',\n",
    "                    'Coordinates': {'y': '52', 'x': '568'},\n",
    "                    'AdditionalProperties': {'Title': 'S', 'Relevance': '7.0'}},\n",
    "         'Bronchitis': {'States': {'no': {}, 'yes': {}},\n",
    "                        'role': 'chance',\n",
    "                        'type': 'finiteStates',\n",
    "                        'Coordinates': {'y': '181', 'x': '698'},\n",
    "                        'AdditionalProperties': {'Title': 'B', 'Relevance': '7.0'}},\n",
    "         'VisitToAsia': {'States': {'no': {}, 'yes': {}},\n",
    "                         'role': 'chance',\n",
    "                         'type': 'finiteStates',\n",
    "                         'Coordinates': {'y': '58', 'x': '290'},\n",
    "                         'AdditionalProperties': {'Title': 'A', 'Relevance': '7.0'}},\n",
    "         'Tuberculosis': {'States': {'no': {}, 'yes': {}},\n",
    "                          'role': 'chance',\n",
    "                          'type': 'finiteStates',\n",
    "                          'Coordinates': {'y': '150', 'x': '201'},\n",
    "                          'AdditionalProperties': {'Title': 'T', 'Relevance': '7.0'}},\n",
    "         'X-ray': {'States': {'no': {}, 'yes': {}},\n",
    "                   'role': 'chance',\n",
    "                   'AdditionalProperties': {'Title': 'X', 'Relevance': '7.0'},\n",
    "                   'Coordinates': {'y': '322', 'x': '252'},\n",
    "                   'Comment': 'Indica si el test de rayos X ha sido positivo',\n",
    "                   'type': 'finiteStates'},\n",
    "         'Dyspnea': {'States': {'no': {}, 'yes': {}},\n",
    "                     'role': 'chance',\n",
    "                     'type': 'finiteStates',\n",
    "                     'Coordinates': {'y': '321', 'x': '533'},\n",
    "                     'AdditionalProperties': {'Title': 'D', 'Relevance': '7.0'}},\n",
    "         'TuberculosisOrCancer': {'States': {'no': {}, 'yes': {}},\n",
    "                                  'role': 'chance',\n",
    "                                  'type': 'finiteStates',\n",
    "                                  'Coordinates': {'y': '238', 'x': '336'},\n",
    "                                  'AdditionalProperties': {'Title': 'E', 'Relevance': '7.0'}},\n",
    "         'LungCancer': {'States': {'no': {}, 'yes': {}},\n",
    "                        'role': 'chance',\n",
    "                        'type': 'finiteStates',\n",
    "                        'Coordinates': {'y': '152', 'x': '421'},\n",
    "                        'AdditionalProperties': {'Title': 'L', 'Relevance': '7.0'}}}\n",
    "edges = {'LungCancer': {'TuberculosisOrCancer': {'directed': 'true'}},\n",
    "         'Smoker': {'LungCancer': {'directed': 'true'},\n",
    "                    'Bronchitis': {'directed': 'true'}},\n",
    "         'Dyspnea': {},\n",
    "         'X-ray': {},\n",
    "         'VisitToAsia': {'Tuberculosis': {'directed': 'true'}},\n",
    "         'TuberculosisOrCancer': {'X-ray': {'directed': 'true'},\n",
    "                                  'Dyspnea': {'directed': 'true'}},\n",
    "         'Bronchitis': {'Dyspnea': {'directed': 'true'}},\n",
    "         'Tuberculosis': {'TuberculosisOrCancer': {'directed': 'true'}}}\n",
    "\n",
    "cpds = [{'Values': np.array([[0.95, 0.05], [0.02, 0.98]]),\n",
    "         'Variables': {'X-ray': ['TuberculosisOrCancer']}},\n",
    "        {'Values': np.array([[0.7, 0.3], [0.4,  0.6]]),\n",
    "         'Variables': {'Bronchitis': ['Smoker']}},\n",
    "        {'Values':  np.array([[0.9, 0.1,  0.3,  0.7], [0.2,  0.8,  0.1,  0.9]]),\n",
    "         'Variables': {'Dyspnea': ['TuberculosisOrCancer', 'Bronchitis']}},\n",
    "        {'Values': np.array([[0.99], [0.01]]),\n",
    "         'Variables': {'VisitToAsia': []}},\n",
    "        {'Values': np.array([[0.5], [0.5]]),\n",
    "         'Variables': {'Smoker': []}},\n",
    "        {'Values': np.array([[0.99, 0.01], [0.9, 0.1]]),\n",
    "         'Variables': {'LungCancer': ['Smoker']}},\n",
    "        {'Values': np.array([[0.99, 0.01], [0.95, 0.05]]),\n",
    "         'Variables': {'Tuberculosis': ['VisitToAsia']}},\n",
    "        {'Values': np.array([[1, 0, 0, 1], [0, 1, 0, 1]]),\n",
    "         'Variables': {'TuberculosisOrCancer': ['LungCancer', 'Tuberculosis']}}]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's create a `BayesianModel` for this data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pgmpy.models import BayesianModel\n",
    "from pgmpy.factors.discrete import TabularCPD\n",
    "\n",
    "model = BayesianModel(edges_list)\n",
    "\n",
    "for node in nodes:\n",
    "    for key, value in nodes[node].items():\n",
    "        model.nodes[node][key] = value\n",
    "\n",
    "for u in edges.keys():\n",
    "    for v in edges[u].keys():\n",
    "        #import pdb; pdb.set_trace()\n",
    "        for key, value in edges[u][v].items():\n",
    "            model.edges[(u, v)][key] = value\n",
    "\n",
    "tabular_cpds = []\n",
    "for cpd in cpds:\n",
    "    var = list(cpd['Variables'].keys())[0]\n",
    "    evidence = cpd['Variables'][var]\n",
    "    values = cpd['Values']\n",
    "    states = len(nodes[var]['States'])\n",
    "    evidence_card = [len(nodes[evidence_var]['States'])\n",
    "                     for evidence_var in evidence]\n",
    "    tabular_cpds.append(\n",
    "        TabularCPD(var, states, values, evidence, evidence_card))\n",
    "\n",
    "model.add_cpds(*tabular_cpds)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pgmpy.readwrite import ProbModelXMLWriter, get_probmodel_data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get the data which we need to give to the ProbModelXMLWriter to get the corresponding fileformat we need to use the method get_probmodel_data. This method is only specific to ProbModelXML file, for other file formats we would directly pass the model to the given Writer Class."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<ProbModelXML formatVersion=\"1.0\">\n",
      "  <ProbNet type=\"BayesianNetwork\">\n",
      "    <Variables>\n",
      "      <Variable name=\"Bronchitis\" role=\"chance\" type=\"finiteStates\">\n",
      "        <Coordinates x=\"698\" y=\"181\" />\n",
      "        <Property name=\"Relevance\" value=\"7.0\" />\n",
      "        <Property name=\"Title\" value=\"B\" />\n",
      "        <States>\n",
      "          <State name=\"no\">\n",
      "            <AdditionalProperties />\n",
      "          </State>\n",
      "          <State name=\"yes\">\n",
      "            <AdditionalProperties />\n",
      "          </State>\n",
      "        </States>\n",
      "      </Variable>\n",
      "      <Variable name=\"Dyspnea\" role=\"chance\" type=\"finiteStates\">\n",
      "        <Coordinates x=\"533\" y=\"321\" />\n",
      "        <Property name=\"Relevance\" value=\"7.0\" />\n",
      "        <Property name=\"Title\" value=\"D\" />\n",
      "        <States>\n",
      "          <State name=\"no\">\n",
      "            <AdditionalProperties />\n",
      "          </State>\n",
      "          <State name=\"yes\">\n",
      "            <AdditionalProperties />\n",
      "          </State>\n",
      "        </States>\n",
      "      </Variable>\n",
      "      <Variable name=\"LungCancer\" role=\"chance\" type=\"finiteStates\">\n",
      "        <Coordinates x=\"421\" y=\"152\" />\n",
      "        <Property name=\"Relevance\" value=\"7.0\" />\n",
      "        <Property name=\"Title\" value=\"L\" />\n",
      "        <States>\n",
      "          <State name=\"no\">\n",
      "            <AdditionalProperties />\n",
      "          </State>\n",
      "          <State name=\"yes\">\n",
      "            <AdditionalProperties />\n",
      "          </State>\n",
      "        </States>\n",
      "      </Variable>\n",
      "      <Variable name=\"Smoker\" role=\"chance\" type=\"finiteStates\">\n",
      "        <Coordinates x=\"568\" y=\"52\" />\n",
      "        <Property name=\"Relevance\" value=\"7.0\" />\n",
      "        <Property name=\"Title\" value=\"S\" />\n",
      "        <States>\n",
      "          <State name=\"no\">\n",
      "            <AdditionalProperties />\n",
      "          </State>\n",
      "          <State name=\"yes\">\n",
      "            <AdditionalProperties />\n",
      "          </State>\n",
      "        </States>\n",
      "      </Variable>\n",
      "      <Variable name=\"Tuberculosis\" role=\"chance\" type=\"finiteStates\">\n",
      "        <Coordinates x=\"201\" y=\"150\" />\n",
      "        <Property name=\"Relevance\" value=\"7.0\" />\n",
      "        <Property name=\"Title\" value=\"T\" />\n",
      "        <States>\n",
      "          <State name=\"no\">\n",
      "            <AdditionalProperties />\n",
      "          </State>\n",
      "          <State name=\"yes\">\n",
      "            <AdditionalProperties />\n",
      "          </State>\n",
      "        </States>\n",
      "      </Variable>\n",
      "      <Variable name=\"TuberculosisOrCancer\" role=\"chance\" type=\"finiteStates\">\n",
      "        <Coordinates x=\"336\" y=\"238\" />\n",
      "        <Property name=\"Relevance\" value=\"7.0\" />\n",
      "        <Property name=\"Title\" value=\"E\" />\n",
      "        <States>\n",
      "          <State name=\"no\">\n",
      "            <AdditionalProperties />\n",
      "          </State>\n",
      "          <State name=\"yes\">\n",
      "            <AdditionalProperties />\n",
      "          </State>\n",
      "        </States>\n",
      "      </Variable>\n",
      "      <Variable name=\"VisitToAsia\" role=\"chance\" type=\"finiteStates\">\n",
      "        <Coordinates x=\"290\" y=\"58\" />\n",
      "        <Property name=\"Relevance\" value=\"7.0\" />\n",
      "        <Property name=\"Title\" value=\"A\" />\n",
      "        <States>\n",
      "          <State name=\"no\">\n",
      "            <AdditionalProperties />\n",
      "          </State>\n",
      "          <State name=\"yes\">\n",
      "            <AdditionalProperties />\n",
      "          </State>\n",
      "        </States>\n",
      "      </Variable>\n",
      "      <Variable name=\"X-ray\" role=\"chance\" type=\"finiteStates\">\n",
      "        <Comment>Indica si el test de rayos X ha sido positivo</Comment>\n",
      "        <Coordinates x=\"252\" y=\"322\" />\n",
      "        <Property name=\"Relevance\" value=\"7.0\" />\n",
      "        <Property name=\"Title\" value=\"X\" />\n",
      "        <States>\n",
      "          <State name=\"no\">\n",
      "            <AdditionalProperties />\n",
      "          </State>\n",
      "          <State name=\"yes\">\n",
      "            <AdditionalProperties />\n",
      "          </State>\n",
      "        </States>\n",
      "      </Variable>\n",
      "    </Variables>\n",
      "    <Links>\n",
      "      <Link directed=\"true\" var1=\"Bronchitis\" var2=\"Dyspnea\">\n",
      "        <AdditionalProperties />\n",
      "      </Link>\n",
      "      <Link directed=\"true\" var1=\"LungCancer\" var2=\"TuberculosisOrCancer\">\n",
      "        <AdditionalProperties />\n",
      "      </Link>\n",
      "      <Link directed=\"true\" var1=\"Smoker\" var2=\"Bronchitis\">\n",
      "        <AdditionalProperties />\n",
      "      </Link>\n",
      "      <Link directed=\"true\" var1=\"Smoker\" var2=\"LungCancer\">\n",
      "        <AdditionalProperties />\n",
      "      </Link>\n",
      "      <Link directed=\"true\" var1=\"Tuberculosis\" var2=\"TuberculosisOrCancer\">\n",
      "        <AdditionalProperties />\n",
      "      </Link>\n",
      "      <Link directed=\"true\" var1=\"TuberculosisOrCancer\" var2=\"Dyspnea\">\n",
      "        <AdditionalProperties />\n",
      "      </Link>\n",
      "      <Link directed=\"true\" var1=\"TuberculosisOrCancer\" var2=\"X-ray\">\n",
      "        <AdditionalProperties />\n",
      "      </Link>\n",
      "      <Link directed=\"true\" var1=\"VisitToAsia\" var2=\"Tuberculosis\">\n",
      "        <AdditionalProperties />\n",
      "      </Link>\n",
      "    </Links>\n",
      "    <Potentials>\n",
      "      <Potential role=\"conditionalProbability\" type=\"Table\">\n",
      "        <Variables>\n",
      "          <Variable name=\"X-ray\" />\n",
      "          <Variable name=\"TuberculosisOrCancer\" />\n",
      "        </Variables>\n",
      "        <Values>0.95 0.05 0.02 0.98 </Values>\n",
      "      </Potential>\n",
      "      <Potential role=\"conditionalProbability\" type=\"Table\">\n",
      "        <Variables>\n",
      "          <Variable name=\"Bronchitis\" />\n",
      "          <Variable name=\"Smoker\" />\n",
      "        </Variables>\n",
      "        <Values>0.7 0.3 0.4 0.6 </Values>\n",
      "      </Potential>\n",
      "      <Potential role=\"conditionalProbability\" type=\"Table\">\n",
      "        <Variables>\n",
      "          <Variable name=\"Dyspnea\" />\n",
      "          <Variable name=\"Bronchitis\" />\n",
      "          <Variable name=\"TuberculosisOrCancer\" />\n",
      "        </Variables>\n",
      "        <Values>0.9 0.1 0.3 0.7 0.2 0.8 0.1 0.9 </Values>\n",
      "      </Potential>\n",
      "      <Potential role=\"conditionalProbability\" type=\"Table\">\n",
      "        <Variables>\n",
      "          <Variable name=\"VisitToAsia\" />\n",
      "        </Variables>\n",
      "        <Values>0.99 0.01 </Values>\n",
      "      </Potential>\n",
      "      <Potential role=\"conditionalProbability\" type=\"Table\">\n",
      "        <Variables>\n",
      "          <Variable name=\"Smoker\" />\n",
      "        </Variables>\n",
      "        <Values>0.5 0.5 </Values>\n",
      "      </Potential>\n",
      "      <Potential role=\"conditionalProbability\" type=\"Table\">\n",
      "        <Variables>\n",
      "          <Variable name=\"LungCancer\" />\n",
      "          <Variable name=\"Smoker\" />\n",
      "        </Variables>\n",
      "        <Values>0.99 0.01 0.9 0.1 </Values>\n",
      "      </Potential>\n",
      "      <Potential role=\"conditionalProbability\" type=\"Table\">\n",
      "        <Variables>\n",
      "          <Variable name=\"Tuberculosis\" />\n",
      "          <Variable name=\"VisitToAsia\" />\n",
      "        </Variables>\n",
      "        <Values>0.99 0.01 0.95 0.05 </Values>\n",
      "      </Potential>\n",
      "      <Potential role=\"conditionalProbability\" type=\"Table\">\n",
      "        <Variables>\n",
      "          <Variable name=\"TuberculosisOrCancer\" />\n",
      "          <Variable name=\"LungCancer\" />\n",
      "          <Variable name=\"Tuberculosis\" />\n",
      "        </Variables>\n",
      "        <Values>1.0 0.0 0.0 1.0 0.0 1.0 0.0 1.0 </Values>\n",
      "      </Potential>\n",
      "    </Potentials>\n",
      "    <AdditionalConstraints />\n",
      "    <AdditionalProperties />\n",
      "    <DecisionCriteria />\n",
      "  </ProbNet>\n",
      "</ProbModelXML>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "model_data = get_probmodel_data(model)\n",
    "writer = ProbModelXMLWriter(model_data=model_data)\n",
    "print(writer.__str__().decode('utf-8'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To write the xml data into the file we can use the method `write_file` of the given Writer class."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [],
   "source": [
    "writer.write_file('probmodelxml.pgmx')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## General WorkFlow of the readwrite module"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "pgmpy.readwrite.[fileformat]Reader is base class for reading the given file format. Replace file format with the desired fileforamt from which you want to read the file. In this base class there are different methods defined to parse the given file. For example for XMLBelief Network various methods which are defined are as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pgmpy.readwrite.XMLBeliefNetwork import XBNReader\n",
    "reader = XBNReader('../files/xmlbelief.xml')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`get_model`: It returns an instance of the given model, for ex, BayesianModel in cases of XMLBelief format."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['a', 'b', 'c', 'd', 'e']\n",
      "[('a', 'b'), ('a', 'c'), ('b', 'd'), ('c', 'd'), ('c', 'e')]\n"
     ]
    }
   ],
   "source": [
    "model = reader.get_model()\n",
    "print(model.nodes())\n",
    "print(model.edges())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "pgmpy.readwrite.[fileformat]Writer is base class for writing the model into the given file format. It takes a model as an argument which can be an instance of BayesianModel, MarkovModel. Replace file fomat with the desired fileforamt from which you want to read the file. In this base class there are different methods defined to set the contents of the new file to be created from the given model. For example for XMLBelief Network various methods such as set_analysisnotebook, etc are defined which helps to set up the network data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pgmpy.models import BayesianModel\n",
    "from pgmpy.factors.discrete import TabularCPD\n",
    "import numpy as np\n",
    "nodes = {'c': {'STATES': ['Present', 'Absent'],\n",
    "               'DESCRIPTION': '(c) Brain Tumor',\n",
    "               'YPOS': '11935',\n",
    "               'XPOS': '15250',\n",
    "               'TYPE': 'discrete'},\n",
    "         'a': {'STATES': ['Present', 'Absent'],\n",
    "               'DESCRIPTION': '(a) Metastatic Cancer',\n",
    "               'YPOS': '10465',\n",
    "               'XPOS': '13495',\n",
    "               'TYPE': 'discrete'},\n",
    "         'b': {'STATES': ['Present', 'Absent'],\n",
    "               'DESCRIPTION': '(b) Serum Calcium Increase',\n",
    "               'YPOS': '11965',\n",
    "               'XPOS': '11290',\n",
    "               'TYPE': 'discrete'},\n",
    "         'e': {'STATES': ['Present', 'Absent'],\n",
    "               'DESCRIPTION': '(e) Papilledema',\n",
    "               'YPOS': '13240',\n",
    "               'XPOS': '17305',\n",
    "               'TYPE': 'discrete'},\n",
    "         'd': {'STATES': ['Present', 'Absent'],\n",
    "               'DESCRIPTION': '(d) Coma',\n",
    "               'YPOS': '12985',\n",
    "               'XPOS': '13960',\n",
    "               'TYPE': 'discrete'}}\n",
    "model = BayesianModel([('b', 'd'), ('a', 'b'), ('a', 'c'), ('c', 'd'), ('c', 'e')])\n",
    "cpd_distribution = {'a': {'TYPE': 'discrete', 'DPIS': np.array([[0.2, 0.8]])},\n",
    "                    'e': {'TYPE': 'discrete', 'DPIS': np.array([[0.8, 0.2],\n",
    "                                                                [0.6, 0.4]]), 'CONDSET': ['c'], 'CARDINALITY': [2]},\n",
    "                    'b': {'TYPE': 'discrete', 'DPIS': np.array([[0.8, 0.2],\n",
    "                                                                [0.2, 0.8]]), 'CONDSET': ['a'], 'CARDINALITY': [2]},\n",
    "                    'c': {'TYPE': 'discrete', 'DPIS': np.array([[0.2, 0.8],\n",
    "                                                                [0.05, 0.95]]), 'CONDSET': ['a'], 'CARDINALITY': [2]},\n",
    "                    'd': {'TYPE': 'discrete', 'DPIS': np.array([[0.8, 0.2],\n",
    "                                                                [0.9, 0.1],\n",
    "                                                                [0.7, 0.3],\n",
    "                                                                [0.05, 0.95]]), 'CONDSET': ['b', 'c'], 'CARDINALITY': [2, 2]}}\n",
    "\n",
    "tabular_cpds = []\n",
    "for var, values in cpd_distribution.items():\n",
    "    evidence = values['CONDSET'] if 'CONDSET' in values else []\n",
    "    cpd = values['DPIS']\n",
    "    evidence_card = values['CARDINALITY'] if 'CARDINALITY' in values else []\n",
    "    states = nodes[var]['STATES']\n",
    "    cpd = TabularCPD(var, len(states), cpd,\n",
    "                     evidence=evidence,\n",
    "                     evidence_card=evidence_card)\n",
    "    tabular_cpds.append(cpd)\n",
    "model.add_cpds(*tabular_cpds)\n",
    "\n",
    "for var, properties in nodes.items():\n",
    "    for key, value in properties.items():\n",
    "        model.nodes[var][key] = value\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pgmpy.readwrite.XMLBeliefNetwork import XBNWriter\n",
    "writer = XBNWriter(model = model)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
